package com.starryx.blog.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.Servlet;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect     // 作为一个切面类
@Component  // 让 spring boot 扫描到（放进 Spring 容器中）
public class LogAspect {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //                  所有访问权限修饰的，在 com.starryx.blog.web 包下的，所有类的，所有任意参数的方法
    @Pointcut("execution(* com.starryx.blog.web.*.*(..))")     // 定义一个切面，参数：规定拦截那些类，不会递归拦截包中包的类
    public void log() {

    }

    // 1
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {     // JoinPoint : 切面对象，用于获取调用方法的信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        //                      类名.方法名
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url, ip, classMethod, args);
        logger.info("Request ： {}", requestLog);

    }

    // 3
    @After("log()")
    public void doAfter() {
//        logger.info("--------doAfter--------");
    }

    // 4
    @AfterReturning(returning = "result", pointcut = "log()")
    public void doAfterReturn(Object result) {
        logger.info("Result : {}", result);
    }

    private class RequestLog {
        private String url;             // 请求 url
        private String ip;              // 访问者 ip
        private String classMethod;     // 调用方法 classMethod
        private Object[] args;          // 参数 args

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "RequestLog{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }

}
